<template>

    <div><!--  style="height: 100%;background: #002833;"-->
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="epoch_range">
                <el-input v-model="formInline.epoch_range" placeholder="epoch_range" ></el-input>
            </el-form-item>
            <el-form-item label="lr">
                <el-select v-model="formInline.lr" placeholder="lr">
                    <el-option label="0.01" value="0.01">0.01</el-option>
                    <el-option label="0.02" value="0.02">0.02</el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">run</el-button>
            </el-form-item>
        </el-form>

        <div id="terminal" ref="terminal"></div> //terminal容器
    </div>
</template>

<script>

    // 引入xterm，请注意这里和3.x版本的引入路径不一样
    import { Terminal } from "xterm"
    import "xterm/css/xterm.css"
    import "xterm/lib/xterm.js"
    import api from '@/api/train_network'
    let term
    export default {
        name: "train_network",
        data() {
            return {
                shellWs: "",
                term: "", // 保存terminal实例
                ws: "",
                rows: 40,
                cols: 100,
                formInline: {
                    epoch_range: 10,
                    lr: ''
                },
                // path: "ws://127.0.0.1:8000/django-api/train/websocket",
                websock: ""
            }
        },

        created() {
            // this.initWebSocket()
            // this.wsShell();
        },

        mounted() {
            // let _this = this;
            // 获取容器宽高/字号大小，定义行数和列数
            // this.rows = document.querySelector(".indexContainer").offsetHeight / 16 - 5;
            // this.cols = document.querySelector(".indexContainer").offsetWidth / 14;
            // 实例化terminal实例
            this.term = term = new Terminal({
                rendererType: "canvas", //渲染类型
                rows: 40, //行数
                // cols: parseInt(_this.cols), // 不指定行数，自动回车后光标从下一行开始
                convertEol: true, //启用时，光标将设置为下一行的开头
                //   scrollback: 50, //终端中的回滚量
                disableStdin: false, //是否应禁用输入。
                cursorStyle: "underline", //光标样式
                cursorBlink: true, //光标闪烁
                theme: {
                    foreground: "#7e9192", //字体
                    background: "#002833", //背景色
                    cursor: "help", //设置光标
                    lineHeight: 16
                }
            });

            // 挂载到dom
            this.term.open(this.$refs["terminal"]);
            // // 换行并输入起始符“$”
            // term.prompt = () => {
            //     term.write("\r\n$ ");
            // };
            // term.prompt();
            // this.term = term
            // term._initialized = true;
            this.term.writeln("Welcome to use Superman... ");
            // this.initWebSocket()
        },
        methods: {
            onSubmit: function () {
                let params = {
                    "epoch_range": this.formInline.epoch_range,
                    "lr": this.formInline.lr
                }
                api.runTrain(params).then(res => {
                    this.$store.commit("mutationsExecutionId",res.executionId)
                    this.initWebSocket()
                }).catch(err => {
                    console.log(err)
                })
            },
            initWebSocket: function (params) {
                const wsuri = "ws://127.0.0.1:8000/django-api/train/websocket" + "/" + this.$store.state.executionId
                if (this.websock) {
                    this.websock.close()
                }
                this.websock = new WebSocket(wsuri);
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onclose = this.websocketclose;
                console.log('store.executionId', this.$store.state.executionId)
            },
            websocketonopen (e) { //连接建立之后执行send方法发送数据
                console.log('WebSocket已经打开: ')
                console.log(e)
            },
            websocketonerror () { //连接建立失败重连
                console.log('WebSocket发生错误: ')
                this.initWebSocket();
            },
            websocketonmessage (e) { //数据接收
                console.log('WebSocket收到消息: ' + e.data)
                let json_data = JSON.parse(e.data)
                console.log(this.$store.state.executionId)
                if (this.$store.state.executionId === json_data['executionId']) {
                    term.writeln(json_data['message'])
                }
            },
            websocketsend (Data) { //数据发送
                this.websock.send(Data)
            },
            websocketclose (e) { //关闭
                console.log('断开连接', e)
            },
            onSend(data) {
                data = this.base.isObject(data) ? JSON.stringify(data) : data;
                data = this.base.isArray(data) ? data.toString() : data;
                data = data.replace(/\\\\/, "\\");
                this.shellWs.onSend(data);
            },

            //删除左右两端的空格
            trim(str) {
                return str.replace(/(^\s*)|(\s*$)/g, "");
            }
        }
    };
</script>

